﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private string pubKey = "0230a768c7dae8b2d729a11806001e080607eed3047514f92d181b93e71e0d9728";
        private string priKey = "ad9e1083c6f140b39a9dfcf96804fd58ff9120efad6ccbac9861a90beddb61f3";
        CaShareEncryptTool caShareEncryptTool = new CaShareEncryptTool();
        CaShareSignTool caShareSignTool = new CaShareSignTool();
        private string signCallBackUrl = "";
        private async Task<CaShareConfig> GetCaShareConfig()
        {
            SM2Crypto sM2Crypto = new SM2Crypto(pubKey, priKey);
            //获取互认组件配置
            string url = "http://120.27.249.148:8081/caapi/config/get";

            var header=new Dictionary<string, string>();
            header["platFormCode"] = "12620000224333349J";
            header["systemCode"] = "Body001";

            string postJson = JsonConvert.SerializeObject(new { caShareComponentsCode = "" });
            postJson=sM2Crypto.Encrypt(pubKey,postJson);

            string sign=sM2Crypto.Sign(postJson,priKey);
            header["signValue"] = sign;


            var result = await HttpTool.PostDataAsync(url, postJson, header);
            if(result.StartsWith("04"))
            {
                result=sM2Crypto.Decrypt(priKey,result);
            }
            var json = JsonConvert.DeserializeObject<JObject>(result);
            if (json["code"].Value<int>() == 0)
            {
                var data = json["data"].Value<JObject>();
                var systemCode = data["platformCode"].Value<string>();
                var apiUrl = data["apiUrl"].Value<string>();
                var clientId = data["clientId"].Value<string>();
                var clientSecret = data["clientSecret"].Value<string>();
                var signatureSecret = data["signatureSecret"].Value<string>();
                var accessKeySecret= data["aesSecretKey"].Value<string>();
                signCallBackUrl= data["signCallBackUrl"].Value<string>();
                CaShareConfig caShareConfig = new CaShareConfig()
                {
                    TradingSystemCode = systemCode,
                    CaShareComponentServiceUrl = apiUrl,
                    ClientId = clientId,
                    ClientSecret = clientSecret,
                    SignatureSecret = signatureSecret,
                    //AccessKeySecret = accessKeySecret,
                    ServiceUrl=apiUrl
                };
                return caShareConfig;
            }
            return null;
        }

        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            //获取互认组件配置

            CaShareConfig caShareConfig = await GetCaShareConfig();
            if (caShareConfig == null)
            {
                MessageBox.Show("获取互认组件配置失败");
                return;
            }

            List<WaitEncryptionFile> waitEncryptionFiles = new List<WaitEncryptionFile>()
                {
                    new WaitEncryptionFile()
                    {
                        AwaitingEncryptionFileName="test.pdf",
                        awaitingEncryptionFilePath="c:\\test.pdf",
                        fileType="pdf"
                    }
                };
            EncryptedFile encryptedFile = new EncryptedFile()
            {
                EncryptedFileZipName = "encrypted.zip",
                CryptedFileExportPath = "c:\\"
            };

            caShareEncryptTool.Start();
            await caShareEncryptTool.WebSocket(waitEncryptionFiles, encryptedFile, caShareConfig);
        }

        /// <summary>
        /// 签章文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //获取互认组件配置

            CaShareConfig caShareConfig = await GetCaShareConfig();
            if (caShareConfig == null)
            {
                MessageBox.Show("获取互认组件配置失败");
                return;
            }

            List<WaitSignFile> waitSignFiles = new List<WaitSignFile>()
            {
                new WaitSignFile()
                {
                    AwaitingSignatureFilePath="c:\\pdf\\test2.pdf",
                    AwaitingSignatureFileName="test2.pdf",
                    AwaitingSignatureFileType="pdf",
                    SignatureFileSavePath="c:\\pdf\\test_signed.pdf",
                    SignatureFileName="test_signed.pdf",
                }
            };

            SealInfo sealInfo = new SealInfo()
            {
                Dpi = 86,
                Transparency = 0.8f,
                SealImgMaxValue = 150
            };

            caShareSignTool.Start();
            //List<WaitSignFile> waitSignFiles, SealInfo sealInfo, CaShareConfig caShareConfig,string callbackUrl
            await caShareSignTool.WebSocket(waitSignFiles, sealInfo, caShareConfig, signCallBackUrl);
        }
    }


    /// <summary>
    /// 互认组件配置
    /// </summary>
    public class CaShareConfig
    {
        [JsonProperty("tradingSystemCode")]
        public string TradingSystemCode { get; set; }
        /// <summary>
        /// 加密客户端使用的服务地址
        /// </summary>
        [JsonProperty("caShareComponentServiceUrl")]
        public string CaShareComponentServiceUrl { get; set; }
        [JsonProperty("clientId")]
        public string ClientId { get; set; }
        [JsonProperty("clientSecret")]
        public string ClientSecret { get; set; }
        [JsonProperty("signatureSecret")]
        public string SignatureSecret { get; set; }

        //[JsonProperty("accessKeySecret")]
        //public string AccessKeySecret { get; set; }

        /// <summary>
        /// 签章客户端使用的服务地址
        /// </summary>

        [JsonProperty("serviceUrl")]
        public string ServiceUrl { get; set; }
    }
}